package com.sj.purchase.modules.cost.listener;

import com.sj.purchase.modules.cost.event.RunTaskEvent;
import com.sj.purchase.modules.cost.config.task.compute.ComputeTaskManager;
import com.sj.purchase.modules.cost.domain.SucTask;
import com.sj.purchase.modules.cost.event.AfterSyncEvent;
import com.sj.purchase.modules.cost.service.ProfitService;
import com.sj.purchase.modules.cost.service.SucTaskService;
import com.sj.purchase.modules.cost.service.UniqueCodeService;
import com.sj.purchase.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 监听事件
 * Created by MaJinGe on 17-11-09.
 */
@Component
public class GlobalListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalListener.class);

    @Autowired
    private SucTaskService sucTaskService;

    @Autowired
    private ComputeTaskManager computeTaskManager;
    @Autowired
    private ProfitService profitService;

    @Autowired
    private UniqueCodeService uniqueCodeService;

    /**
     * 同步任务之后
     *
     * @param afterSyncEvent
     */
    @EventListener(classes = AfterSyncEvent.class)
    public void afterSyncTask(AfterSyncEvent afterSyncEvent) {
        try {
            uniqueCodeService.saveUniqueCode(DateUtils.yesterDay());
        }catch (Exception e){
            LOGGER.info("-----唯一码数据匹配失败-----");
        }finally {
            computeTaskManager.runTask(SucTask.TaskType.COMPUTE_COST_PRICE, afterSyncEvent.getTaskDay());
            computeTaskManager.runTask(SucTask.TaskType.COMPUTE_STOCK_CONTRAST, afterSyncEvent.getTaskDay());
        }
    }

    /**
     * 同步
     *
     * @param runTaskEvent
     */
    @EventListener(classes = RunTaskEvent.class)
    public void saveSucTask(RunTaskEvent runTaskEvent) {
        LOGGER.info("[EventListener] :=> [{}] :=> 完成{}", runTaskEvent.getTaskDay(), runTaskEvent.getTaskType().getName());
        sucTaskService.save(runTaskEvent.getTaskType(), runTaskEvent.getTaskDay());
        //库存明细同步完毕后计算利润
        if (SucTask.TaskType.SYNC_INVENTORY.equals(runTaskEvent.getTaskType())) {
            profitService.save(runTaskEvent.getTaskDay());
        }
    }
}
